package com.roy.eureka.client.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;
import com.roy.eureka.api.dto.User;
import com.roy.eureka.client.service.HystrixCacheService;
import com.roy.eureka.client.service.HystrixCollapserService;

@RestController
public class HystrixController {

	@Autowired
	private HystrixCollapserService collService;
	@Autowired
	private HystrixCacheService cacheService;
	/**
	 * 将多个相似的请求聚合到一起，完成请求。
	 * @return
	 */
	@GetMapping("/testCollapser")
	public Object testCollapser() throws InterruptedException, ExecutionException {
		List<User> res = new ArrayList<>();
		Future<User> f1 = collService.getMember(1);
		Future<User> f2 = collService.getMember(2);
		Future<User> f3 = collService.getMember(3);
		res.add(f1.get());
		res.add(f2.get());
		res.add(f3.get());
		return res;
	}
	/**
	 * 测试hystrix请求缓存
	 * @return
	 */
	@GetMapping("/testCache")
	public Object testCache(String userId) {
		User res = new User();
		for(int i = 0 ; i < 5 ; i ++) {
			res = cacheService.cacheUser(userId);
		}
		return res;
	}
	
	@GetMapping("/testCacheRemove")
	public Object testCacheRemove() {
		User user = null;
		user = cacheService.getCache("11");//加入缓存
		user = cacheService.getCache("11");//从缓存中获取
		user = cacheService.getCache("11");//从缓存中获取
		
		cacheService.removeCache("11");//删除缓存
		
		user = cacheService.getCache("11");//重新加入缓存。
		return user;
	}
	
	@PostConstruct
	public void init() {
		HystrixRequestContext ctx = HystrixRequestContext.initializeContext();
	}
}
